package com.atguigu.tingshu.comment.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.tingshu.comment.service.CommentService;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.util.MongoUtil;
import com.atguigu.tingshu.model.comment.Comment;
import com.atguigu.tingshu.vo.album.TrackStatMqVo;
import com.atguigu.tingshu.vo.comment.CommentVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.UUID;

@Service
@Slf4j
public class CommentServiceImpl implements CommentService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RabbitService rabbitService;

    @Override
    public IPage<CommentVo> findCommentPage(IPage<CommentVo> page, Long albumId, Long trackId) {
        Criteria criteria = Criteria.where("albumId").is(albumId).and("trackId").is(trackId);
        Query query = new Query(criteria);
        query.with(Pageable.ofSize((int) page.getSize()).withPage((int) page.getCurrent() - 1));
        page.setTotal(mongoTemplate.count(query, Comment.class));
        page.setPages((int) page.getTotal() / page.getSize() + 1);
        return page.setRecords(mongoTemplate.find(query, CommentVo.class, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.COMMENT, trackId)));
    }

    @Override
    public void save(CommentVo commentVo) {
        mongoTemplate.save(commentVo, MongoUtil.getCollectionName(MongoUtil.MongoCollectionEnum.COMMENT, commentVo.getTrackId()));
        // 专辑下的评论数+1 声音下的评论数+1
        TrackStatMqVo trackStatMqVo = new TrackStatMqVo();
        trackStatMqVo.setBusinessNo(UUID.randomUUID().toString().replaceAll("-",""));
        trackStatMqVo.setAlbumId(commentVo.getAlbumId());
        trackStatMqVo.setTrackId(commentVo.getTrackId());
        trackStatMqVo.setStatType(SystemConstant.ALBUM_STAT_COMMENT);
        trackStatMqVo.setCount(1);
        rabbitService.sendMessage(MqConst.EXCHANGE_ALBUM,MqConst.ROUTING_ALBUM_STAT_UPDATE, JSONObject.toJSONString(trackStatMqVo));
        trackStatMqVo.setStatType(SystemConstant.TRACK_STAT_COMMENT);
        rabbitService.sendMessage(MqConst.EXCHANGE_TRACK,MqConst.ROUTING_TRACK_STAT_UPDATE, JSONObject.toJSONString(trackStatMqVo));
    }
}
